package code.lewdy.mail;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;

public class TestMail {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		searchTest();
	}

	public static void searchTest() {
		String host = "pop.sina.com"; //imap.qq.com
		String user = "newdoo@sina.com"; // 506641796@qq.com
		String password = "thejiang";  //c==456java
		
//		String user = "lewdy007@sina.com"; // 506641796@qq.com
//		String password = "lewdy123";  //c==456java

		String mbox = "INBOX";
		String protocol = "pop3"; // imap
		boolean debug = false;
		try {
			// Get a Properties object 系统属性
			Properties props = System.getProperties();

			// Get a Session object
			// 邮件会话对象
			Session session = Session.getInstance(props, null);
			session.setDebug(debug);

			// Get a Store object
			Store store = null;

			if (protocol != null)
				store = session.getStore(protocol);
			else
				store = session.getStore();

			// Connect
			if (host != null || user != null || password != null) {

				store.connect(host, user, password);

			}

			// Open the Folder

			Folder folder = null;

			folder = store.getDefaultFolder();

			if (folder == null) {
				System.out.println("Cant find default namespace");
				System.exit(1);
			}

			folder = folder.getFolder(mbox);

			if (folder == null) {
				System.out.println("Invalid folder");
				System.exit(1);
			}

			folder.open(Folder.READ_ONLY);

			//System.out.println("folder list length:" + folder.list().length);
		
		
Message[] msgs2 = folder.getMessages();
Message msg;
int fetchSize = 100; //检索数量
int count = 0;
for(int i=msgs2.length-1; i>=0; i--,count++ ){
	dumpPart(msgs2[i]);
	if(true)
		continue;

	msg = msgs2[i];
	System.out.println("发送人:"+MailUtil.getMailAddress(msg.getFrom()[0]));
	System.out.println(msg);
	if(null == msg.getContent()){
		System.out.println("null---------" + msg.getSubject());
		continue;
	}
	Multipart mtp = (Multipart) msg.getContent();
	
	for(int k=0; k<mtp.getCount(); k++){
		BodyPart body = mtp.getBodyPart(k);
		System.out.println("Multipart"+k+"#####################");
		System.out.println(body.getContent());
		String str = "";
		StringBuffer sb = new StringBuffer();
		
		InputStream is = body.getInputStream();  
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "GB2312"));
		while ((str = reader.readLine()) != null) {
			sb.append(str);
		}
		reader.close();
		is.close();

		System.out.println("正文："+sb.toString());
	}
}


			folder.close(false);
			store.close();
		} catch (Exception e) {
			System.out.println("Oops, got exception! " + e.getMessage());
			e.printStackTrace();
		}
	}

	public static void dumpPart(Part p) throws Exception {
		if (p instanceof Message) {
			Message m = (Message) p;
			Address[] a;
			// FROM
			if ((a = m.getFrom()) != null) {
				for (int j = 0; j < a.length; j++)
					System.out.println("FROM: " + a[j].toString());
			}

			// TO
			if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
				for (int j = 0; j < a.length; j++)
					System.out.println("TO: " + a[j].toString());
			}

			// SUBJECT
			System.out.println("SUBJECT: " + m.getSubject());

			// DATE
			Date d = m.getSentDate();
			System.out.println("SendDate: "
					+ (d != null ? d.toLocaleString() : "UNKNOWN"));

			// FLAGS:
			Flags flags = m.getFlags();
			StringBuffer sb = new StringBuffer();
			Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

			boolean first = true;
			for (int i = 0; i < sf.length; i++) {
				String s;
				Flags.Flag f = sf[i];
				if (f == Flags.Flag.ANSWERED)
					s = "\\Answered";
				else if (f == Flags.Flag.DELETED)
					s = "\\Deleted";
				else if (f == Flags.Flag.DRAFT)
					s = "\\Draft";
				else if (f == Flags.Flag.FLAGGED)
					s = "\\Flagged";
				else if (f == Flags.Flag.RECENT)
					s = "\\Recent";
				else if (f == Flags.Flag.SEEN)
					s = "\\Seen";
				else
					continue; // skip it
				if (first)
					first = false;
				else
					sb.append(' ');
				sb.append(s);
			}

			String[] uf = flags.getUserFlags(); // get the user flag strings
			for (int i = 0; i < uf.length; i++) {
				if (first)
					first = false;
				else
					sb.append(' ');
				sb.append(uf[i]);
			}
			System.out.println("FLAGS = " + sb.toString());
		}

		System.out.println("CONTENT-TYPE: " + p.getContentType());
		
		/*
		 * Dump input stream InputStream is = ((MimeMessage)m).getInputStream();
		 * int c; while ((c = is.read()) != -1) System.out.write(c);
		 */

		Object o = p.getContent();
		if (o instanceof String) {
			//System.out.println("This is a String");
			System.out.println((String) o);
		} else if (o instanceof Multipart) {
			System.out.println("This is a Multipart");
			Multipart mp = (Multipart) o;
			int count = mp.getCount();
			for (int i = 0; i < count; i++)
				dumpPart(mp.getBodyPart(i));
		} else if (o instanceof InputStream) {
			System.out.println("This is just an input stream");
			InputStream is = (InputStream) o;
			int c;
			while ((c = is.read()) != -1)
				System.out.write(c);
		}
	}

}
